<?php
/**
 *    Copyright 2010 Show Framework(www.showframework.cn)
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 * 
 *        http://www.apache.org/licenses/LICENSE-2.0
 * 
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

/**
 * 配置类
 * 
 * @package Show
 * @name Show_Config
 * @author show
 * @since v0.6
 */
class Show_Config implements Show_Config_Interface
{
    /**
     * 存放已经加载的配置
     *
     * @var array
     */
    protected $items;
    
    /**
     * 从数组构建一个配置，可以支持多级分类
     * $config = new Show_Config(array('version' => '1.0', 'author' => array('main' => 'show')));
     * echo $config->version //1.0
     * echo $config->author->main //show
     *
     * @param array $array
     * @return void
     */
    public function __construct(array $array)
    {
        $this->items = array();
        
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $this->items[$key] = new self($value);
            } else {
                $this->items[$key] = $value;
            }
        }
    }
    
    /**
     * 支持$config->name的访问方式
     *
     * @param string $name
     * @return mixed
     */
    public function __get($name)
    {
        return $this->get($name);
    }
    
    /**
     * 获取名称为 $name 的一个配置或一组配置
     *
     * @param string $name
     * @return mixed
     */
    public function get($name)
    {
        $result = null;
        if (array_key_exists($name, $this->items)) {
            $result = $this->items[$name];
        } else {
            trigger_error("配置项($name)不存在，请查看配置文件中是否设置此配置", E_USER_WARNING);
        }
        return $result;
    }
    
    /**
     * 配置中是否有 以 $name 命名的一项
     *
     * @param string $name
     * @return bool
     */
    public function has($name)
    {
        return array_key_exists($name, $this->items);
    }
    
    /**
     * 将自己转换成array
     *
     * @return array
     */
    public function toArray()
    {
        $array = array();
        foreach ($this->items as $key => $value) {
            if ($value instanceof Show_Config_Interface) {
                $array[$key] = $value->toArray();
            } else {
                $array[$key] = $value;
            }
        }
        return $array;
    }
}
?>